package gov.nhso.prov.acc.utils;

import gov.nhso.prov.acc.core.ConfigBundle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.isud.core.ISUD;

@SuppressWarnings("rawtypes")
public class SysAuth {
	private HttpServletRequest request;
	public String schema = ConfigBundle.getValue("SCHEMA");
	private List<Map> menuSys = null;
	private Map<String, String> menuAuth = new HashMap<String, String>();
	
	protected SysAuth (HttpServletRequest request) {
		this.request = request;
	}
	
	public void getMenu(ISUD dao, String roleId) throws Exception {
		StringBuffer sql = new StringBuffer();
		List menu = (List) this.request.getSession().getAttribute("menuSys");
		if (menu == null || (menu != null)) {
			sql.append("SELECT A.MENU_ID, A.MENU_NAME, A.MENU_URL, B.AUTH, A.MENU_GROUP, A.MENU_PARENT ");
			sql.append("FROM " + this.schema + ".ACC67_MENU A ");
			sql.append("JOIN " + this.schema + ".ACC67_ROLE_MENU B ");
			sql.append("ON A.MENU_ID = B.MENU_ID ");
			sql.append("WHERE B.ROLE_ID = " + roleId + " ");
			sql.append("AND A.ACTIVE = 'Y' ");
			sql.append("AND B.ACTIVE = 'Y' ");
			sql.append("ORDER BY A.MENU_GROUP ASC, A.MENU_SEQ ASC, A.MENU_ID ASC");
			Map<String, String> screenCode = new HashMap<String, String>();
			List items = dao.listDataSql(sql.toString());
			String screenDesc = "";
			for (int i = 0; i < items.size(); i++) {
				Map data = (Map) items.get(i);
				this.menuAuth.put(dao.chkData(data.get("MENU_ID")), this.authBit2Str(dao.chkData(data.get("AUTH"))));
				if (this.menuSys == null) {
					this.menuSys = new ArrayList<Map>();
				}
				if (dao.chkData(data.get("MENU_URL")).equals("")) {
					screenDesc = dao.chkData(data.get("MENU_NAME"));
				}
				screenCode.put(dao.chkData(data.get("MENU_ID")), "&nbsp;" + screenDesc + " >> " + dao.chkData(data.get("MENU_NAME")));
				this.menuSys.add(data);
			}
			this.request.getSession().setAttribute("screenCode", screenCode);
			this.request.getSession().setAttribute("menuSys", this.menuSys);
			this.request.getSession().setAttribute("menuAuth", this.menuAuth);
		}
	}
	
	public String authBit2Str(String bit) {
		String auth = "";
		String str = "SIUD";
		char[] c = bit.toCharArray();
		char[] s = str.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '1') {
				auth += s[i];
			}
		}
		return auth;
	}
	
}
